import { defineStore } from 'pinia';
import type { UserInfo } from '@/api/user/type';
import { getUserData } from '@/api/user';

export default defineStore('user', () => {
  const token = ref<string>();
  const userInfo = ref<UserInfo>();

  const getToken = computed(() => uni.getStorageSync('token'));
  const getUserInfo = async () => {
    const { data } = await getUserData();
    uni.setStorageSync('userInfo', data);
    userInfo.value = data;
  };

  function setToken(newToken: string) {
    token.value = newToken;
    uni.setStorageSync('token', newToken);
  }

  function setUserInfo(info: any) {
    userInfo.value = info;
    uni.setStorageSync('userInfo', info);
  }

  function clearUserInfo() {
    token.value = '';
    userInfo.value = undefined;
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');
  }

  return {
    token,
    userInfo,
    getToken,
    getUserInfo,
    setToken,
    setUserInfo,
    clearUserInfo,
  };
});
